<?php

declare(strict_types=1);

namespace app\api\controller\Product;

use app\BaseController;
use app\common\model\Product\Cart as CartModel;
use app\common\model\Product\Product as ProductModel;
use app\common\model\User\User as UserModel;
use Exception;
use think\exception\ValidateException;
use app\common\validate\Product\Cart as CartValiDate;

class Cart extends BaseController
{
    public function index()
    {
        $userid = $this->request->param('userid');

        $CartList = CartModel::withJoin(['product'])->where(['userid' => $userid])->select();

        if (!$CartList) {
            $this->error('暂无数据');
        }

        $this->success('查询成功', null, $CartList);
    }


    public function add()
    {
        try {
            // 用户id
            $userid = $this->request->param('userid');
            // 商品id
            $proid = $this->request->param('proid');
            // 查询商品
            $product = ProductModel::find($proid);
            // 查询用户
            $user = UserModel::find($userid);
            // 判断商品是否存在
            if (!$product) {
                throw new Exception('商品不存在');
            }
            // 判断用户是否存在
            if (!$user) {
                throw new Exception('用户不存在');
            }
            // 查询商品是否存在于购物车
            $Cart = CartModel::where(['userid' => $userid, 'proid' => $proid])->find();

            if ($Cart) {
                if ($Cart['nums'] >= $product['stock']) {
                    throw new Exception('商品库存不足');
                }
                // 判断是否有会员价
                $price = $product['vip_price'] ? $product['vip_price'] : $product['price'];
                // 封装数据
                $data = [
                    'userid' => $userid,
                    'proid' => $proid,
                    'nums' => $Cart['nums'] + 1,
                    'price' => $price,
                    'total' => bcmul((string)($price), (string)($Cart['nums'] + 1)),
                ];
                // 执行更新语句
                $result = CartModel::update($data, ['id' => $Cart['id']]);
                // 判断结果
                if ($result === FALSE) {
                    throw new Exception('添加失败');
                }
            } else {
                if ($product['stock'] == 0) {
                    throw new Exception('商品库存不足');
                }
                // 判断是否有会员价
                $price = $product['vip_price'] ? $product['vip_price'] : $product['price'];
                // 封装数据
                $data = [
                    'userid' => $userid,
                    'proid' => $proid,
                    'nums' => 1,
                    'price' => $price,
                    'total' => $price,
                ];
                // 验证数据
                validate(CartValiDate::class)->check($data);
                // 执行新增语句
                $result = CartModel::create($data);
                // 判断是否成功
                if ($result === FALSE) {
                    throw new Exception('添加失败');
                }
            }
        } catch (ValidateException $e) {
            $this->error($e->getError());
        } catch (Exception $error) {
            $this->error($error->getMessage());
        }

        $this->success('添加成功');
    }
    // 购物车商品数量
    public function stepper()
    {
        $params = $this->request->param();

        $Cart = CartModel::find($params['cartid']);

        if (!$Cart) {
            $this->error('该购物车记录不存在');
        }

        $Cart->total = bcmul((string)$Cart['price'], (string)$params['nums']);

        $Cart->nums = $params['nums'];

        $result = $Cart->save();

        if ($result !== FALSE) {
            $this->success('更新商品的数量成功');
        } else {
            $this->error('更新商品的数量成功');
        }
    }
    public function del()
    {
        $id = $this->request->param('cartid');
        $Cart = CartModel::find($id);
        if (!$Cart) {
            $this->error('查询购物车数据失败');
        }
        $result = CartModel::destroy($id);
        if ($result === FALSE) {
            $this->error('移除购物车商品失败');
        }
        $this->success('移除购物车商品成功');
    }
    // 订单支付
    public function confirm()
    {
        $ids = $this->request->param('ids');
        $proid = $this->request->param('proid');
        $action = $this->request->param('action');
        if ($action == 'info') {
            $list = ProductModel::find($proid);
            if (!$list) {
                $this->error('商品不存在');
            }
            $list['price'] = $list['vip_price'] ? $list['vip_price'] : $list['price'];
        } else {
            $list = CartModel::withJoin(['product'])->whereIn('cart.id', $ids)->select();
            if (!$list) {
                $this->error('商品不存在');
            }
        }
        $this->success('查询成功', null, $list);
    }
}
